#include "StdAfx.h"
#include "StreamPage.h"
#include "MemoryManager.h"
#include "BufferConstraint.h"
#include "Element.h"
StreamPage::StreamPage( )
{
	this->buffer = MemoryManager::getInstance()->getOnePage();


}

StreamPage::~StreamPage(void)
{
}
void StreamPage::setNextFreePosition(CHUNK_INDEX_TYPE chunk, MemoryPosition& memoryPosition)
{
	char* buffer = this->buffer;
	int p = 0;
	memcpy(buffer + chunk* CHUNK_SIZE + p, &memoryPosition.pageIndex, sizeof(PAGE_INDEX_TYPE));
	p += sizeof(memoryPosition.pageIndex);
	memcpy(buffer+ chunk* CHUNK_SIZE + p, &memoryPosition.chunkIndex, sizeof(CHUNK_INDEX_TYPE));

}
void StreamPage::getNextFreePosition(CHUNK_INDEX_TYPE chunk, MemoryPosition& memoryPosition)
{
	char* buffer = this->buffer;
	int p = 0;
	
	memoryPosition.pageIndex = *(PAGE_INDEX_TYPE*)(buffer + chunk* CHUNK_SIZE + p);
	p += sizeof(PAGE_INDEX_TYPE);
	memoryPosition.chunkIndex = *(CHUNK_INDEX_TYPE*)(buffer + chunk* CHUNK_SIZE + p);
}

void StreamPage::setValue( CHUNK_INDEX_TYPE chunkIndex,Element& element)
{
	assert(element.getSize()<=CHUNK_SIZE);
	assert(chunkIndex<=CHUNK_NUMBER_ONE_PAGE);
	char* chunkPostion = this->buffer + chunkIndex*CHUNK_SIZE;
	int p= sizeof(CHUNK_INDEX_TYPE)+sizeof(PAGE_INDEX_TYPE);
	memcpy(chunkPostion + p , &element.timestamp,TIMESTAMP_SIZE);
	p += TIMESTAMP_SIZE;
	memcpy(chunkPostion + p, &element.id, DOCUMENT_IDENTIFIER_SIZE);
	p += DOCUMENT_IDENTIFIER_SIZE;
	memcpy(chunkPostion + p, &element.mark, MARK_SIZE);
	p += MARK_SIZE;
	memcpy(chunkPostion + p, element.document.objdata(),element.document.objsize());
}
void StreamPage::getValue(CHUNK_INDEX_TYPE chunkIndex,Element&element)
{
	assert(chunkIndex<=CHUNK_NUMBER_ONE_PAGE);
	char* chunkPostion = this->buffer + chunkIndex*CHUNK_SIZE;
	int p= sizeof(CHUNK_INDEX_TYPE)+sizeof(PAGE_INDEX_TYPE);
	element.timestamp = *(Timestamp*)(chunkPostion+p);
	p += TIMESTAMP_SIZE;
	element.id = *(DocumentId*)(chunkPostion+p);
	p += DOCUMENT_IDENTIFIER_SIZE;
	element.mark = *(Mark*) (chunkPostion+p);
	p += MARK_SIZE;
	element.document = Document(chunkPostion+p);

}